package org.jeecg.modules.cows.wx.service.impl;

import org.jeecg.modules.cows.wx.constant.WechatConstant;
import org.jeecg.modules.cows.wx.dto.WechatLoginDTO;
import org.jeecg.modules.cows.wx.dto.WechatTokenDTO;
import org.jeecg.modules.cows.wx.service.WechatInfoService;
import org.jeecg.modules.cows.wx.utils.HttpUtils;
import org.springframework.stereotype.Service;


import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Service
@Slf4j
public class WechatInfoServiceImpl implements WechatInfoService {
    @Override
    public WechatTokenDTO getToken() {
        WechatTokenDTO wechatTokenDTO = WechatTokenDTO.builder().build();
        String result = HttpUtils.getUrl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WechatConstant.APP_ID +
                "&secret="+WechatConstant.SECRET);
        JSONObject jo = JSONObject.fromObject(result);

        wechatTokenDTO.setAccessToken(jo.getString("access_token"));
        wechatTokenDTO.setExpiresIn(jo.getLong("expires_in"));
        return wechatTokenDTO;
    }

    @Override
    public WechatLoginDTO wxLogin(String jsCode) {
        WechatLoginDTO wechatLoginDTO = WechatLoginDTO.builder().build();
        String result = HttpUtils.getUrl("https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" + WechatConstant.APP_ID +
                "&secret="+WechatConstant.SECRET+"&js_code="+jsCode);
        JSONObject jo = JSONObject.fromObject(result);
        log.info("wechat jscode2session return :{}", jo.toString());
        wechatLoginDTO.setOpenId(jo.getString("openid"));
        wechatLoginDTO.setSessionKey(jo.getString("session_key"));
        return wechatLoginDTO;
    }
}
